package fxwebserversocket

import (
	"fmt"
	"golang.org/x/net/websocket"
	"net"
	"net/http"
	"os"
)

var TCP_Serve_Addr string

func WebSocketStart(addr string,tcpaddr string) {
	TCP_Serve_Addr=tcpaddr
	http.Handle("/", websocket.Handler(Echo))

	if err := http.ListenAndServe(addr, nil); err != nil {

		fmt.Println(err)
	}
}

func Echo(conn *websocket.Conn) {
	ipStr := conn.RemoteAddr().String()
	exit_sta:=false
	fmt.Printf("wsEcho start ws conn ,TCP_Serve_Addr=%s,ip=%s\n",TCP_Serve_Addr ,ipStr)

	defer func() {

		fmt.Printf("DialTCP  err recover()") //有效
		fmt.Println(recover()) //有效
		if exit_sta!=true{
			conn.Close()
		}
	}()

	serverAddr, err := net.ResolveTCPAddr("tcp4", TCP_Serve_Addr)
	if err != nil {
		fmt.Println(os.Stderr, "Fatal error: ", err)
		return
	}
	//建立服务器连接
	tcpconn, err := net.DialTCP("tcp", nil, serverAddr)
	defer func() {
		tcpconn.Close()
		fmt.Printf("Echo tcpconn conn close,ip=%s\n", ipStr)
	}()
	if err != nil {
		return
	}
	go func(){
		defer func() {
			exit_sta=true
			conn.Close()
		}()
		for {
			var webbuf [1024]byte
			webbufLen, err := tcpconn.Read(webbuf[:])
			if err != nil {
				fmt.Printf("Echo err,ip=%s err: %v\n", ipStr, err)
				break
			}
			conn.Write(webbuf[:webbufLen])
			fmt.Printf("Echo read,ip=%s,data: %v\n", ipStr, webbuf[:webbufLen])
		}
	}()
	for {
		var wsbuf [1024]byte
		tcpbufLen, err := conn.Read(wsbuf[:])

		if err != nil {
			fmt.Printf("Echo err,ip=%s err: %v\n",ipStr, err)
			break
		}
		tcpconn.Write(wsbuf[:tcpbufLen])
		fmt.Printf("Echo read,ip=%s,data: %v\n", ipStr, wsbuf[:tcpbufLen])
	}
}



